<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="学校名称" prop="schoolName">
          <el-input
            v-model="queryParams.schoolName"
            placeholder="请输入学校名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="显示顺序" prop="orderNum">
          <el-input
            v-model="queryParams.orderNum"
            placeholder="请输入显示顺序"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="负责人" prop="leader">
          <el-input
            v-model="queryParams.leader"
            placeholder="请输入负责人"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入联系电话"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学校人数" prop="schoolNum">
          <el-input
            v-model="queryParams.schoolNum"
            placeholder="请输入学校人数"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="queryParams.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input
            v-model="queryParams.province"
            placeholder="请输入省份"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input
            v-model="queryParams.city"
            placeholder="请输入市"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="区" prop="district">
          <el-input
            v-model="queryParams.district"
            placeholder="请输入区"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="经度" prop="longitude">
          <el-input
            v-model="queryParams.longitude"
            placeholder="请输入经度"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input
            v-model="queryParams.latitude"
            placeholder="请输入纬度"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:school:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:school:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:school:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:school:import']"
            >导入</el-button>
          </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:school:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="schoolList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="学校id" align="center" prop="id" /> -->
        <el-table-column label="学校名称" align="center" prop="schoolName" />
        <el-table-column label="显示顺序" align="center" prop="orderNum" />
        <el-table-column label="负责人" align="center" prop="leader" />
        <el-table-column label="经销商" align="center" prop="dealerName" />
        <el-table-column label="联系电话" align="center" prop="phone" />
        <el-table-column label="学校类型 自定义" align="center" prop="schoolType" />
        <el-table-column label="学校人数" align="center" prop="schoolNum" />
        <el-table-column label="邮箱" align="center" prop="email" />
        <el-table-column label="省份" align="center" prop="province" />
        <el-table-column label="市" align="center" prop="city" />
        <el-table-column label="区" align="center" prop="district" />
        <el-table-column label="经度" align="center" prop="longitude" />
        <el-table-column label="纬度" align="center" prop="latitude" />
        <el-table-column label="包含区域" align="center" prop="region" />
        <el-table-column label="状态" align="center" prop="statusName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:school:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:school:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改学校对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
            <el-form-item label="学校名称" prop="schoolName">
            <el-input v-model="form.schoolName" placeholder="请输入学校名称" :maxlength="50" show-word-limit
                clearable :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="显示顺序" prop="orderNum">
            <el-input-number v-model="form.orderNum" placeholder="请输入显示顺序" controls-position=right>
            </el-input-number>
            </el-form-item>
            <el-form-item label="负责人" prop="leader">
            <el-input v-model="form.leader" placeholder="请输入负责人" :maxlength="50" show-word-limit clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" clearable :style="{width: '100%'}">
            </el-input>
            </el-form-item>
            <el-form-item label="学校人数" prop="schoolNum">
            <el-input-number v-model="form.schoolNum" placeholder="学校人数" controls-position=right></el-input-number>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" clearable :style="{width: '100%'}">
            </el-input>
            </el-form-item>
            <el-form-item label="省份" prop="province">
            <el-input v-model="form.province" placeholder="请输入省份" :maxlength="50" show-word-limit clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="市" prop="city">
            <el-input v-model="form.city" placeholder="请输入市" :maxlength="50" show-word-limit clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="区" prop="district">
            <el-input v-model="form.district" placeholder="请输入区" :maxlength="50" show-word-limit clearable
                :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="分销商" prop="dealerId">
            <el-select v-model="form.dealerId" placeholder="请选择分销商" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in dealerIdOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
            </el-form-item>
            <el-form-item label="包含区域" prop="region">
            <el-input v-model="form.region" type="textarea" placeholder="请输入包含区域" :maxlength="500"
                show-word-limit :autosize="{minRows: 2, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status" size="small">
                <el-radio-button v-for="(item, index) in statusOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-radio-button>
            </el-radio-group>
            </el-form-item>
            <el-form-item label="图片" prop="fileId" required>
              <el-upload ref="schoolImage" :limit="1" list-type="picture-card" :on-remove="handleSchoolImageRemove" :before-upload="schoolImageBeforeUpload" :on-success="uploadSchoolImage" :file-list="schoolImageList" action="https://meiyang.zoorank.com/dev-file/upload">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="位置">
              <div>
              {{ this.form.addressName }}
              </div>
              <el-button type="text" @click="handleSelectPostion">点击选择位置</el-button>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="选择位置"
        :visible.sync="mapDialogVisible"
        width="60%">
        <Mapview ref="mapview"  :longitude="this.form.longitude" :latitude = "this.form.latitude" @selectPostion="selectPostion"></Mapview>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="cancelMapDialog">取 消</el-button> -->
          <el-button type="primary" @click="mapDialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 学校导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    </div>
  </template>

  <script>
  import { listSchool, getSchool, delSchool, addSchool, updateSchool } from "@/api/system/school";
  import { listDealer} from "@/api/system/dealer";
  import Mapview from "../../../components/MapView/MapContainer.vue"
  import { getToken } from "@/utils/auth";
  export default {
    name: "School",
    components: {
      Mapview
    },
    data() {
      return {
        mapDialogVisible: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 学校表格数据
        schoolList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          schoolName: null,
          orderNum: null,
          leader: null,
          phone: null,
          schoolType: null,
          schoolNum: null,
          email: null,
          province: null,
          city: null,
          district: null,
          longitude: null,
          latitude: null,
          region: null,
          status: null,
        },
        queryDealerSelectParams: {
          pageNum: 1,
          pageSize: 1000
        },
         // 学校导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/school/importData"
      },
        // 表单参数
        form: {
            schoolName: undefined,
            orderNum: 0,
            leader: undefined,
            phone: undefined,
            schoolNum: 0,
            email: undefined,
            province: undefined,
            city: undefined,
            district: undefined,
            longitude: undefined,
            latitude: undefined,
            region: undefined,
            addressName:undefined,
            status: '0',
        },
        schoolImageList:[],
        // 表单校验
        rules: {
        schoolName: [{
          required: true,
          message: '请输入学校名称',
          trigger: 'blur'
        }],
        orderNum: [{
          required: true,
          message: '请输入显示顺序',
          trigger: 'blur'
        }],
        leader: [{
          required: true,
          message: '请输入负责人',
          trigger: 'blur'
        }],
        phone: [{
          required: true,
          message: '请输入联系电话',
          trigger: 'blur'
        }, {
          pattern: /^1[3456789]\d{9}$/,
          message: '请输入正确的手机号码',
          trigger: 'blur'
        }],
        schoolNum: [{
          required: true,
          message: '学校人数',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }, {
          pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
          message: '请输入正确的邮箱',
          trigger: 'blur'
        }],
        province: [{
          required: true,
          message: '请输入省份',
          trigger: 'blur'
        }],
        city: [{
          required: true,
          message: '请输入市',
          trigger: 'blur'
        }],
        district: [{
          required: true,
          message: '请输入区',
          trigger: 'blur'
        }],
        longitude: [{
          required: true,
          message: '经度',
          trigger: 'blur'
        }],
        latitude: [{
          required: true,
          message: '纬度',
          trigger: 'blur'
        }],
        dealerId: [{
          required: true,
          message: '请选择分销商',
          trigger: 'change'
        }],
        region: [{
          required: true,
          message: '请输入包含区域',
          trigger: 'blur'
        }],
        status: [{
          required: true,
          message: '状态不能为空',
          trigger: 'change'
        }],
      },
      statusOptions: [{
        "label": "正常",
        "value": '0'
      }, {
        "label": "停用",
        "value": '1'
      }],
      dealerIdOptions: [],
      };
    },

    created() {
      this.getList();
      this.getDealerSelect();
    },
    methods: {
       /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "学校导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/school/importTemplate', {
      }, `school_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
      /**
       *显示地图，并设置地点
       */
      handleSelectPostion(){
        this.mapDialogVisible = true
        var that = this;
        this.$nextTick(() => {
          this.$refs['mapview'].setMarker([that.form.longitude, that.form.latitude])
        })
      },
      /**
       * 隐藏地图
       */
      // cancelMapDialog(){
      //   this.form.longitude = 0;
      //   this.form.latitude = 0;
      //   this.mapDialogVisible = false;
      // },
      /**
       * 设置选择的坐标（子组件调用）
       * @param {*} longitude
       * @param {*} latitude
       */
      selectPostion(longitude,latitude,addressName){
        console.log('1',longitude,latitude,addressName)
        this.form.latitude = latitude;
        this.form.longitude = longitude;
        this.form.addressName = addressName;
      },
      /**
       * 查询经销
       */
      getDealerSelect() {
          listDealer(this.queryDealerSelectParams).then(response => {
              let dealerList = response.rows;
              if(dealerList){
                  let arr = []
                  dealerList.forEach(element => {
                      arr.push({"label": element.dealerName,"value": element.id})
                  });
                  this.dealerIdOptions = arr
              }
          });
      },
      /** 查询学校列表 */
      getList() {
        this.loading = true;
        listSchool(this.queryParams).then(response => {
          this.schoolList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          schoolName: null,
          orderNum: null,
          leader: null,
          phone: null,
          schoolType: null,
          schoolNum: null,
          email: null,
          province: null,
          city: null,
          district: null,
          longitude: null,
          latitude: null,
          region: null,
          status: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          fileId:null
        };
        this.schoolImageList= []
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加学校";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getSchool(id).then(response => {
          this.form = response.data;
          this.form.latitude = Number(this.form.latitude)
          this.form.longitude = Number(this.form.longitude);
          if(this.form.fileId){
            this.schoolImageList= [{name:this.form.fileName,url:this.form.fileUrl}]
          }
          this.open = true;
          this.title = "修改学校";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(!this.form.longitude||!this.form.latitude){
              this.$modal.msgWarn("请选择学校位置！");
            }
            if (this.form.id != null) {
              updateSchool(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addSchool(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      uploadSchoolImage(res, file, fileList){
        this.form.fileId = res.data.fileId
      },

      handleSchoolImageRemove(file, fileList){
        this.schoolImageList = [];
        this.form.fileId = null;
      },

      schoolImageBeforeUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        return isRightSize&&isJPG;
    },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除学校编号为"' + ids + '"的数据项？').then(function() {
          return delSchool(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/school/export', {
          ...this.queryParams
        }, `school_${new Date().getTime()}.xlsx`)
      }
    }
  };
  </script>
